package com.inifitness.tenant.core.config.mp.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.inifitness.tenant.core.config.mp.service.EncryptService;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.springframework.stereotype.Component;

/**
 * 数组类型转换 json
 * <p>
 * 主要是用于对象数据 基础类型包装对象不建议用
 *
 * @author sunjinfeng
 * @since 1.0.0
 */
@Log4j2
@Component
@RequiredArgsConstructor
@MappedJdbcTypes(value = {JdbcType.VARCHAR}, includeNullJdbcType = true)
//@MappedTypes(value = {String.class})
public class EncryptTypeHandler<T> extends BaseTypeHandler<T> {

  private final EncryptService encryptService;

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType)
      throws SQLException {
    ps.setString(i, encryptService.encrypt((String) parameter));
  }

  @Override
  public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String columnValue = rs.getString(columnName);
    return CharSequenceUtil.isBlank(columnValue) ? (T) columnValue
        : (T) encryptService.decrypt(columnValue);
  }

  @Override
  public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String columnValue = rs.getString(columnIndex);
    return CharSequenceUtil.isBlank(columnValue) ? (T) columnValue
        : (T) encryptService.decrypt(columnValue);
  }

  @Override
  public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String columnValue = cs.getString(columnIndex);
    return CharSequenceUtil.isBlank(columnValue) ? (T) columnValue
        : (T) encryptService.decrypt(columnValue);
  }
}
